<!--
 * @Author: zgx 2324461523@qq.com
 * @Date: 2024-02-07 15:01:20
 * @LastEditors: zgx 2324461523@qq.com
 * @LastEditTime: 2024-03-02 15:33:49
 * @FilePath: \tph_shop\src\pages\goodsDetail\components\spec.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 商品规格弹出框 -->
<template>
  <vk-data-goods-sku-popup
    ref="skuPopupRef"
    v-model="skuKey"
    border-radius="20"
    :localdata="goodsInfo"
    :mode="skuMode"
    buy-now-background-color="#ff0034"
    @add-cart="addCart"
    @buy-now="buyNow"
  ></vk-data-goods-sku-popup>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
// 引入ts类型
import type { goodsInfoType } from '@/types/goodsDetail'
// 引入仓库
import { useUserStore } from '@/store/modules/user'
// 引入接口函数
import { postAddCartAPI } from '@/api/cart'
import { nowBuyAPI } from '@/api/order'
import type { nowBuyParamsType } from '@/types/order'
// 数量
const num = ref(1)
// 创建仓库
const userStore = useUserStore()
// 模式 1:都显示 2:只显示购物车 3:只显示立即购买
const skuMode = ref(1)
const goodsInfo = ref<goodsInfoType>({} as goodsInfoType)
// sku规格弹出的ref对象
const skuPopupRef = ref()
const skuKey = ref(false)
// 地址id
const addressId = ref('')
const open = (info: goodsInfoType, mode: number, id?: string) => {
  // 赋值
  goodsInfo.value = info
  skuKey.value = true
  skuMode.value = mode
  if (id) {
    addressId.value = id
  }
}
// 添加购物车按钮的回调
const addCart = async (selectShop: any) => {
  // 判断用户是否已登录
  const token = userStore.token!
  if (!token) {
    // 未登录，跳转到登录页面
    uni.navigateTo({ url: '/pages/login/login' })
  } else {
    // 已登录
    const res = await postAddCartAPI({ skuId: selectShop._id, count: selectShop.buy_num })
    if (res.code === '1') {
      // 添加购物车成功
      uni.showToast({ title: '添加成功', icon: 'success' })
      // 关闭商品规格弹窗
      skuKey.value = false
    }
  }
}
// 立即购买按钮的回调
const buyNow = async (selectShop: any) => {
  // 判断用户是否已登录
  const token = userStore.token!
  if (!token) {
    // 未登录，跳转到登录页面
    uni.navigateTo({ url: '/pages/login/login' })
  } else {
    // 整合参数
    const data: nowBuyParamsType = {
      skuId: selectShop._id,
      count: selectShop.buy_num,
      addressId: addressId.value,
    }
    // 调用接口，获取立即购买订单详情
    const res = await nowBuyAPI(data)
    if (res.code === '1') {
      // 跳转到填写订单页
      uni.navigateTo({ url: `/pagesOrder/create/create?nowBuyOrder=${JSON.stringify(res.result)}` })
    }
  }
}
defineExpose({
  open,
})
</script>

<style lang="stylus" scoped></style>
